package it.unibz.easytravel.expenses;

import java.util.Vector;

import it.unibz.easytravel.R;
import it.unibz.easytravel.db.DebtsDbAdapter;
import it.unibz.easytravel.db.PersonDbAdapter;
import it.unibz.easytravel.expenses.statistic.Converter;
import it.unibz.easytravel.expenses.statistic.Statistic;
import it.unibz.easytravel.travel.EditTravel;
import android.app.Activity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class AmountList extends Activity {

	private DebtsDbAdapter mDebtsDb;
	private PersonDbAdapter mPersonsDb;
	
	private static int travel_id;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.expenses_debts_list);
		
		SharedPreferences settings = getSharedPreferences(EditTravel.PREFS_NAME, 0);
		travel_id = settings.getInt(EditTravel.TRAVEL_ID, -1);
	}
	
	public void onResume (){
		super.onResume();
		Display();
	}
	
	void Display() {	
		
		mDebtsDb = new DebtsDbAdapter(this);
		mDebtsDb.open();

		mPersonsDb = new PersonDbAdapter(this);
		mPersonsDb.open();

		Cursor debtsCursor = mDebtsDb.getAllDebts(travel_id);
		startManagingCursor(debtsCursor);

		Vector<Debt> debts = new Vector<Debt>();
		
		while (debtsCursor.moveToNext()) {
			int creditir_id = debtsCursor.getInt(debtsCursor
					.getColumnIndexOrThrow("creditor"));
			int debtor_id = debtsCursor.getInt(debtsCursor
					.getColumnIndexOrThrow("debtor"));
			int amount = debtsCursor.getInt(debtsCursor
					.getColumnIndexOrThrow("amount"));

			debts.addElement(new Debt(mPersonsDb.getName(creditir_id),
					mPersonsDb.getName(debtor_id), amount));
		}

		Statistic stat = new Statistic(debts);
		debts = stat.getDebts();

		LinearLayout mView = (LinearLayout) findViewById(R.id.LLBebtsList);
		mView.removeAllViews();
		int size = debts.size();
		if (size > 0) {
			for (int i = 0; i < size; i++) {
				Debt d = debts.elementAt(i);
				TextView text = new TextView(this);
				text.setText(d.getDebtor() + ">" + d.getCreditor() + " "
						+ Converter.convertToStringMerge(d.getDebt()));
				mView.addView(text);
			}
		} else {
			TextView text = new TextView(this);
			text.setText("Nobody is in debt to anybody.");
			mView.addView(text);
		}

		mDebtsDb.close();
		mPersonsDb.close();
	}
}
